package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	
	public class AirClient extends Sprite {
		private var socket:CustomSocket;
		private var text:TextField;
		public function AirClient() {
			socket = new CustomSocket("localhost", 8098);
			text = new TextField();
			text.text = "send data area";
			text.type = TextFieldType.INPUT;
			text.backgroundColor = 0xaabbcc;
			addChild(text);
			
			var btn:Sprite = new Sprite();
			btn.graphics.beginFill(0x22ddaa);
			btn.graphics.drawRect(0,0,20,20);
			btn.graphics.endFill();
			addChild(btn);
			btn.y = 100;
			btn.addEventListener(MouseEvent.CLICK, sendHandler);
		}
		
		private function sendHandler(evt:MouseEvent):void
		{
			for(var i:int = 0; i < 2000; i++)
			{
				socket.sendRequest(i + "fack");
			}
		}
	}
}

import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
import flash.utils.ByteArray;

class CustomSocket extends Socket {
	private var response:String;
	
	public function CustomSocket(host:String = null, port:uint = 0) {
		super();
		configureListeners();
		if (host && port)  {
			super.connect(host, port);
		}
	}
	
	private function configureListeners():void {
		addEventListener(Event.CLOSE, closeHandler);
		addEventListener(Event.CONNECT, connectHandler);
		addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
	}
	
	private function writeln(str:String):void {
		str += "\n";
		try {
			//writeUTFBytes(str);
			
			//要发送的元数据
			var objByte:ByteArray = new ByteArray();
			objByte.writeObject(str);
			
			//压缩，可以省略
			//objByte.compress();   
			
			//写入数据长度的数据
			var msgByte:ByteArray = new ByteArray();
			msgByte.writeInt(objByte.length); 
			msgByte.writeBytes(objByte, 0, objByte.length); 
			
			writeBytes(msgByte);
		}
		catch(e:IOError) {
			trace(e);
		}
	}
	
	public function sendRequest(msg:String):void {
		trace("sendRequest");
		response = "";
		writeln(msg);
		flush();
	}
	
	private function readResponse():void {
		var str:String = readUTFBytes(bytesAvailable);
		response += str;
	}
	
	private function closeHandler(event:Event):void {
		trace("closeHandler: " + event);
		trace(response.toString());
	}
	
	private function connectHandler(event:Event):void {
		trace("connectHandler: " + event);
		//sendRequest();
	}
	
	private function ioErrorHandler(event:IOErrorEvent):void {
		trace("ioErrorHandler: " + event);
	}
	
	private function securityErrorHandler(event:SecurityErrorEvent):void {
		trace("securityErrorHandler: " + event);
	}
	
	private function socketDataHandler(event:ProgressEvent):void {
		trace("socketDataHandler: " + event);
		readResponse();
	}
}